package com.king.armips.android.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.king.armips.android.R;
import com.king.armips.android.base.BaseActivity;
import com.king.armips.android.utils.FileUtils;

import java.io.File;

public class DocActivity extends BaseActivity {

    public static void start(Context context,String fileName,boolean isCompress,String title){
        Intent intent = new Intent(context,DocActivity.class);
        intent.putExtra("fileName",fileName);
        intent.putExtra("title",title);
        intent.putExtra("isCompress",isCompress);
        context.startActivity(intent);
    }

    private WebView webView;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_doc);

        findViewById(R.id.btn_back).setOnClickListener(v -> finish());

        TextView tvTitle = findViewById(R.id.tv_title);

        Intent intent = getIntent();
        String fileName = intent.getStringExtra("fileName");
        String title = intent.getStringExtra("title");
        boolean isCompress = intent.getBooleanExtra("isCompress",false);

        tvTitle.setText(title);

        initWebView();

        loadAssetFile(fileName,isCompress);

    }

    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {
        webView = findViewById(R.id.web_view);

        WebSettings settings = webView.getSettings();
        settings.setAppCacheEnabled(true); // 开启 Application Caches 功能
        settings.setDomStorageEnabled(true); // 开启 DOM storage API 功能
        settings.setAllowFileAccess(true); // 设置可以访问文件，默认启用
        settings.setJavaScriptEnabled(true); // 如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        settings.setJavaScriptCanOpenWindowsAutomatically(true); // 支持通过JS打开新窗口
        settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        settings.setBlockNetworkImage(false);
        settings.setCacheMode(WebSettings.LOAD_DEFAULT); // 设置缓存模式
    }

    private void loadAssetFile(String fileName,boolean isCompress){
        if (isCompress){
            File indexFile = new File(getFilesDir(),fileName+"/index.html");
            if (!indexFile.exists()){
                FileUtils.unzipAssetFile(this,fileName,indexFile.getParent());
            }

            webView.loadUrl("file://"+indexFile.getAbsolutePath());
        }
        else {
            webView.loadUrl("file:///android_asset/" + fileName);
        }
    }


}
